import os
import time
from datetime import timedelta

import ajson
from flask import Flask, request, jsonify, send_from_directory, Response
from flask_apscheduler import APScheduler
from flask_cors import CORS
# 视图模块
from db_base import UserOrm
from views.admin.api import admin_v
from views.article import article_v
from views.user import user_v

app = Flask(__name__,
            static_folder="./dist/static",
            template_folder="./dist")
app.config["SEND_FILE_MAX_AGE_DEFAULT"] = timedelta(seconds=1)
cors = CORS(app)

UPLOAD_FOLDER = 'avatar'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER  # 设置文件上传的目标文件夹
basedir = os.path.abspath(os.path.dirname(__file__))  # 获取当前项目的绝对路径
ALLOWED_EXTENSIONS = set(['png', 'jpg''JPG', 'PNG''gif', 'GIF'])  # 允许上传的文件后缀

# 统一蓝图导入
app.register_blueprint(article_v, url_prefix="/article")
app.register_blueprint(user_v, url_prefix="/user")
app.register_blueprint(admin_v, url_prefix="/admin")


# 判断文件是否合法
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


@app.route('/avatar/', methods=['POST'], strict_slashes=False)
def avatar():
    file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER'])  # 拼接成合法文件夹地址
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)  # 文件夹不存在就创建
    f = request.files['avatar']  # 从表单的file字段获取文件，avatar为该表单的name值
    user_id = request.form.get('user_id')
    if f and allowed_file(f.filename):  # 判断是否是允许上传的文件类型
        fname = f.filename
        ext = fname.rsplit('.', 1)[1]  # 获取文件后缀
        unix_time = int(time.time())
        new_filename = str(unix_time) + '.' + ext  # 修改文件名
        f.save(os.path.join(file_dir, new_filename))  # 保存文件到upload目录

        u = UserOrm.orm.find('avatar').where(id=user_id).first().end()

        if 'default' not in u.avatar:
            try:
                os.remove(os.path.join(file_dir, u.avatar))
            except:
                pass

        UserOrm.orm.update().set(avatar=new_filename).where(id=user_id).end()

        return jsonify({"code": 0, "message": "上传成功"})
    else:
        return jsonify({"code": 500, "message": f"上传失败,只允许使用后缀为：{ALLOWED_EXTENSIONS}"})


@app.route("/avatar/<path:filename>")
def get_avatar(filename):
    dirpath = os.path.join(app.root_path, 'avatar')
    return send_from_directory(dirpath, filename, as_attachment=True)  # as_attachment=True 一定要写，不然会变成打开，而不是下载


@app.errorhandler(Exception)
def error(e):
    """
    全局异常
    """
    return Response(ajson.aj.parse({
        'message': str(e),
        'code': 500
    }), status=500)


if __name__ == '__main__':
    scheduler = APScheduler()
    scheduler.init_app(app)
    scheduler.start()
    app.run(host='0.0.0.0', port=8000)
